import { ref } from 'vue'
import chatService from '../services/chat.service.js'

export default function useChat() {
    const messages = ref([])
    const currentMessage = ref('')
    const isLoading = ref(false)
    const error = ref(null)
    let currentConnection = null
    let currentBotMessageId = null

    const sendMessage = async () => {
        if (!currentMessage.value.trim() || isLoading.value) return

        error.value = null

        const userMessage = {
            id: Date.now(),
            content: currentMessage.value,
            isUser: true,
            html: ''  // Clear any previous HTML
        }
        messages.value.push(userMessage)

        isLoading.value = true
        currentMessage.value = ''

        currentBotMessageId = 'bot-' + Date.now()
        const botMessage = {
            id: currentBotMessageId,
            content: '',
            isUser: false,
            html: ''  // Initialize HTML content for Markdown
        }
        messages.value.push(botMessage)

        try {
            currentConnection = chatService.sendMessage(
                userMessage.content,
                (data) => {
                    if (data.type === 'chunk') {
                        // Only update the content with the new chunk
                        const botMessage = messages.value.find(m => m.id === currentBotMessageId);
                        if (botMessage) {
                            botMessage.content = data.accumulated;
                            botMessage.html = data.html;
                        }
                    } else if (data.type === 'end') {
                        isLoading.value = false;
                    }
                },
                (err) => {
                    isLoading.value = false;
                    error.value = err;
                }
            );
        } catch (err) {
            isLoading.value = false;
            error.value = err;
        }
    }

    const stopGeneration = () => {
        if (currentConnection && isLoading.value) {
            currentConnection.close();
            isLoading.value = false;
        }
    }

    return {
        messages,
        currentMessage,
        isLoading,
        error,
        sendMessage,
        stopGeneration
    }
}